// import { http } from "@/utils/http";
import { getRouters } from "@/api/menu";
type Result = {
  success: boolean;
  data: Array<any>;
};

// 递归处理路由数据，为所有path节点值前面添加"/"
function addLeadingSlashToPaths(
  routes: Array<any>,
  parentPath: string = ""
): Array<any> {
  return routes.map(route => {
    // 替换路由path中的://符号
    if (route.path && typeof route.path === "string") {
      route.path = route.path.replace(/:\/\//g, "");
    }
    // 处理当前路由的path
    if (
      route.path &&
      typeof route.path === "string" &&
      !route.path.startsWith("/")
    ) {
      route.path = "/" + route.path;
    }
    // 处理当前路由的icon
    if (
      route.meta &&
      route.meta.icon &&
      typeof route.meta.icon === "string" &&
      !route.meta.icon.startsWith("svg-") &&
      !route.meta.icon.includes(":") // 避免处理iconify格式的图标(如ep:home)
    ) {
      route.meta.icon = "svg-" + route.meta.icon;
    }
    // 递归处理子路由
    if (
      route.children &&
      Array.isArray(route.children) &&
      route.children.length > 0
    ) {
      route.children = addLeadingSlashToPaths(route.children);
    }
    // 处理根节点路由：如果是根节点且没有children，则将当前路由作为自身的子路由
    if (parentPath === "/" && route.path && !route.children) {
      // 创建只包含path和meta属性的新路由对象
      const childRoute = { ...route };
      // 设置当前路由的children数组并添加子路由
      route.children = [childRoute];
      // 避免子路由name与父路由name重复
      route.name = route.name + "-";
    }
    return route;
  });
}

export const getAsyncRoutes = () => {
  // return http.request<Result>("get", "/get-async-routes");
  return getRouters<Result>().then(info => {
    const data = addLeadingSlashToPaths(info.data, "/");
    return {
      success: true,
      data: data
    };
  });
};
